#!/bin/bash

# RWA Platform API Curl Tests
# 使用curl命令直接测试所有API端点

BASE_URL="http://localhost:3000"
API_BASE="${BASE_URL}/api/v1"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 测试结果统计
TOTAL_TESTS=0
PASSED_TESTS=0
FAILED_TESTS=0

# 打印测试结果
print_result() {
    local test_name="$1"
    local status="$2"
    local response="$3"
    
    TOTAL_TESTS=$((TOTAL_TESTS + 1))
    
    if [ "$status" = "success" ]; then
        echo -e "${GREEN}✅ PASS${NC}: $test_name"
        PASSED_TESTS=$((PASSED_TESTS + 1))
    else
        echo -e "${RED}❌ FAIL${NC}: $test_name"
        echo -e "${YELLOW}Response:${NC} $response"
        FAILED_TESTS=$((FAILED_TESTS + 1))
    fi
    echo
}

# 测试认证端点
test_auth_endpoints() {
    echo -e "${BLUE}🔐 Testing Authentication Endpoints...${NC}"
    echo "=========================================="
    
    # 测试钱包登录 - 有效数据
    echo "Testing wallet login with valid data..."
    response=$(curl -s -w "\n%{http_code}" -X POST "${API_BASE}/auth/wallet-login" \
        -H "Content-Type: application/json" \
        -d '{
            "walletAddress": "0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8b6",
            "message": "Welcome to RWA Platform! Please sign this message to authenticate.",
            "signature": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
            "fullName": "John Doe"
        }')
    
    http_code=$(echo "$response" | tail -n1)
    response_body=$(echo "$response" | head -n -1)
    
    if [ "$http_code" = "200" ]; then
        print_result "Wallet login with valid data" "success" "$response_body"
        # 提取token用于后续测试
        TOKEN=$(echo "$response_body" | grep -o '"access_token":"[^"]*"' | cut -d'"' -f4)
        echo -e "${GREEN}Token obtained: ${TOKEN:0:20}...${NC}"
    else
        print_result "Wallet login with valid data" "fail" "HTTP $http_code: $response_body"
    fi
    
    # 测试无效的钱包地址
    echo "Testing wallet login with invalid wallet address..."
    response=$(curl -s -w "\n%{http_code}" -X POST "${API_BASE}/auth/wallet-login" \
        -H "Content-Type: application/json" \
        -d '{
            "walletAddress": "invalid-address",
            "message": "Test message",
            "signature": "0x1234567890abcdef",
            "fullName": "Test User"
        }')
    
    http_code=$(echo "$response" | tail -n1)
    response_body=$(echo "$response" | head -n -1)
    
    if [ "$http_code" = "400" ]; then
        print_result "Wallet login with invalid wallet address" "success" "$response_body"
    else
        print_result "Wallet login with invalid wallet address" "fail" "HTTP $http_code: $response_body"
    fi
    
    # 测试空消息
    echo "Testing wallet login with empty message..."
    response=$(curl -s -w "\n%{http_code}" -X POST "${API_BASE}/auth/wallet-login" \
        -H "Content-Type: application/json" \
        -d '{
            "walletAddress": "0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8b6",
            "message": "",
            "signature": "0x1234567890abcdef",
            "fullName": "Test User"
        }')
    
    http_code=$(echo "$response" | tail -n1)
    response_body=$(echo "$response" | head -n -1)
    
    if [ "$http_code" = "400" ]; then
        print_result "Wallet login with empty message" "success" "$response_body"
    else
        print_result "Wallet login with empty message" "fail" "HTTP $http_code: $response_body"
    fi
}

# 测试用户端点
test_user_endpoints() {
    echo -e "${BLUE}👥 Testing User Management Endpoints...${NC}"
    echo "============================================="
    
    if [ -z "$TOKEN" ]; then
        echo -e "${YELLOW}⚠️  No token available, skipping authenticated tests${NC}"
        return
    fi
    
    # 测试获取当前用户信息
    echo "Testing get current user..."
    response=$(curl -s -w "\n%{http_code}" -X GET "${API_BASE}/users/me" \
        -H "Authorization: Bearer $TOKEN")
    
    http_code=$(echo "$response" | tail -n1)
    response_body=$(echo "$response" | head -n -1)
    
    if [ "$http_code" = "200" ]; then
        print_result "Get current user" "success" "$response_body"
    else
        print_result "Get current user" "fail" "HTTP $http_code: $response_body"
    fi
    
    # 测试更新当前用户信息
    echo "Testing update current user..."
    response=$(curl -s -w "\n%{http_code}" -X PATCH "${API_BASE}/users/me" \
        -H "Authorization: Bearer $TOKEN" \
        -H "Content-Type: application/json" \
        -d '{
            "fullName": "Updated Test User",
            "email": "updated@test.com"
        }')
    
    http_code=$(echo "$response" | tail -n1)
    response_body=$(echo "$response" | head -n -1)
    
    if [ "$http_code" = "200" ]; then
        print_result "Update current user" "success" "$response_body"
    else
        print_result "Update current user" "fail" "HTTP $http_code: $response_body"
    fi
    
    # 测试根据ID获取用户
    echo "Testing get user by ID..."
    response=$(curl -s -w "\n%{http_code}" -X GET "${API_BASE}/users/1" \
        -H "Authorization: Bearer $TOKEN")
    
    http_code=$(echo "$response" | tail -n1)
    response_body=$(echo "$response" | head -n -1)
    
    if [ "$http_code" = "200" ]; then
        print_result "Get user by ID" "success" "$response_body"
    else
        print_result "Get user by ID" "fail" "HTTP $http_code: $response_body"
    fi
    
    # 测试根据钱包地址获取用户
    echo "Testing get user by wallet address..."
    response=$(curl -s -w "\n%{http_code}" -X GET "${API_BASE}/users/wallet/0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8b6" \
        -H "Authorization: Bearer $TOKEN")
    
    http_code=$(echo "$response" | tail -n1)
    response_body=$(echo "$response" | head -n -1)
    
    if [ "$http_code" = "200" ]; then
        print_result "Get user by wallet address" "success" "$response_body"
    else
        print_result "Get user by wallet address" "fail" "HTTP $http_code: $response_body"
    fi
    
    # 测试未认证的请求
    echo "Testing unauthenticated request..."
    response=$(curl -s -w "\n%{http_code}" -X GET "${API_BASE}/users/me")
    
    http_code=$(echo "$response" | tail -n1)
    response_body=$(echo "$response" | head -n -1)
    
    if [ "$http_code" = "401" ]; then
        print_result "Unauthenticated request rejection" "success" "$response_body"
    else
        print_result "Unauthenticated request rejection" "fail" "HTTP $http_code: $response_body"
    fi
}

# 测试API文档
test_api_documentation() {
    echo -e "${BLUE}📚 Testing API Documentation...${NC}"
    echo "====================================="
    
    echo "Testing Swagger documentation access..."
    response=$(curl -s -w "\n%{http_code}" -X GET "${BASE_URL}/api/docs")
    
    http_code=$(echo "$response" | tail -n1)
    response_body=$(echo "$response" | head -n -1)
    
    if [ "$http_code" = "200" ] && echo "$response_body" | grep -q "Swagger"; then
        print_result "Swagger documentation access" "success" "Documentation accessible"
    else
        print_result "Swagger documentation access" "fail" "HTTP $http_code: Documentation not accessible"
    fi
}

# 打印测试摘要
print_summary() {
    echo -e "${BLUE}📊 Test Results Summary${NC}"
    echo "========================"
    echo -e "Total Tests: ${YELLOW}$TOTAL_TESTS${NC}"
    echo -e "Passed: ${GREEN}$PASSED_TESTS${NC}"
    echo -e "Failed: ${RED}$FAILED_TESTS${NC}"
    
    if [ $TOTAL_TESTS -gt 0 ]; then
        success_rate=$((PASSED_TESTS * 100 / TOTAL_TESTS))
        echo -e "Success Rate: ${YELLOW}${success_rate}%${NC}"
    fi
    
    echo
    if [ $FAILED_TESTS -eq 0 ]; then
        echo -e "${GREEN}🎉 All tests passed!${NC}"
    else
        echo -e "${RED}⚠️  Some tests failed. Check the output above for details.${NC}"
    fi
}

# 主函数
main() {
    echo -e "${BLUE}🚀 Starting RWA Platform API Tests with cURL...${NC}"
    echo "=================================================="
    echo
    
    # 检查应用程序是否运行
    if ! curl -s "${BASE_URL}/api/docs" > /dev/null 2>&1; then
        echo -e "${RED}❌ Error: Application is not running on ${BASE_URL}${NC}"
        echo "Please start the application with: npm run start:dev"
        exit 1
    fi
    
    echo -e "${GREEN}✅ Application is running on ${BASE_URL}${NC}"
    echo
    
    # 运行测试
    test_auth_endpoints
    test_user_endpoints
    test_api_documentation
    
    # 打印摘要
    print_summary
}

# 运行主函数
main "$@"
